<?php

/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-7-18
 * Time: 11: 32
 */

class Uploader
{
    private $fileField;
    private $file;
    private $base64;
    private $config;
    private $oriName;
    private $fileName;
    private $fullName;
    private $filePath;
    private $fileSize;
    private $fileType;
    private $stateInfo;

    public function __construct($fileField, $config, $type = "upload")
    {
        $this->fileField = $fileField;
        $this->config = $config;
        $this->type = $type;
        if ($type == "remote") {
            $this->saveRemote();
        } else if($type == "base64") {
            $this->upBase64();
        } else {
            $this->upFile();
        }

    }

    private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            //$this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            //return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
		$this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else {
            $this->stateInfo = $this->getStateInfo(0);
        }
    }

    private function upBase64()
    {
        $base64Data = $_POST[$this->fileField];
        $img = base64_decode($base64Data);

        $this->oriName = $this->config['oriName'];
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) {
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else {
            $this->stateInfo = $this->getStateInfo(0);
        }

    }

    private function saveRemote()
    {
        $imgUrl = htmlspecialchars($this->fileField);
        $imgUrl = str_replace("&amp;", "&", $imgUrl);

        if (strpos($imgUrl, "http") !== 0) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
            return;
        }

        $heads = get_headers($imgUrl);
        if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
            $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
            return;
        }

        $fileType = strtolower(strrchr($imgUrl, '.'));
        if (!in_array($fileType, $this->config['allowFiles']) || stristr($heads['Content-Type'], "image")) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
            return;
        }

        ob_start();
        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false // don't follow redirects
            ))
        );
        readfile($imgUrl, false, $context);
        $img = ob_get_contents();
        ob_end_clean();
        preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);

        $this->oriName = $m ? $m[1]:"";
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) {
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else {
            $this->stateInfo = $this->getStateInfo(0);
        }

    }

    private function getStateInfo($errCode)
    {
        switch ($errCode) {
            case 0:
                $msg = "SUCCESS";
                break;
            case 1:
                $msg = lang('plugin/dzapp_base', 'html_1');
                break;
            case 2:
                $msg = lang('plugin/dzapp_base', 'html_2');
                break;
            case 3:
                $msg = lang('plugin/dzapp_base', 'html_3');
                break;
            case 4:
                $msg = lang('plugin/dzapp_base', 'html_4');
                break;
            case 5:
                $msg = lang('plugin/dzapp_base', 'html_5');
                break;
            case "ERROR_TMP_FILE":
                $msg = lang('plugin/dzapp_base', 'html_6');
                break;
            case "ERROR_TMP_FILE_NOT_FOUND":
                $msg = lang('plugin/dzapp_base', 'html_7');
                break;
            case "ERROR_SIZE_EXCEED":
                $msg = lang('plugin/dzapp_base', 'html_8');
                break;
            case "ERROR_TYPE_NOT_ALLOWED":
                $msg = iconv('unicode', 'gbk', lang('plugin/dzapp_base', 'html_9'));
                break;
            case "ERROR_CREATE_DIR":
                $msg = lang('plugin/dzapp_base', 'html_10');
                break;
            case "ERROR_DIR_NOT_WRITEABLE":
                $msg = lang('plugin/dzapp_base', 'html_11');
                break;
            case "ERROR_FILE_MOVE":
                $msg = lang('plugin/dzapp_base', 'html_12');
                break;
            case "ERROR_FILE_NOT_FOUND":
                $msg = lang('plugin/dzapp_base', 'html_13');
                break;
            case "ERROR_WRITE_CONTENT":
                $msg = lang('plugin/dzapp_base', 'html_14');
                break;
            case "ERROR_DEAD_LINK":
                $msg = lang('plugin/dzapp_base', 'html_16');
                break;
            case "ERROR_HTTP_LINK":
                $msg = lang('plugin/dzapp_base', 'html_17');
                break;
            case "ERROR_HTTP_CONTENTTYPE":
                $msg = lang('plugin/dzapp_base', 'html_18');
                break;
            case "ERROR_UNKNOWN":
            default:
                $msg = lang('plugin/dzapp_base', 'html_15');
                break;
        }
        return $msg;
    }

    private function getFileExt()
    {
        return strtolower(strrchr($this->oriName, '.'));
    }

    private function getFullName()
    {
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
        return $format . $ext;
    }

    private function getFileName () {
        return substr($this->filePath, strrpos($this->filePath, '/') + 1);
    }

    private function getFilePath()
    {
        $fullname = $this->fullName;

        if (substr($fullname, 0, 1) != '/') {
            $fullname = '/' . $fullname;
        }

        return DISCUZ_ROOT . $fullname;
    }

    private function checkType()
    {
        return in_array($this->getFileExt(), $this->config["allowFiles"]);
    }

    private function  checkSize()
    {
        return $this->fileSize <= ($this->config["maxSize"]);
    }

    public function getFileInfo()
    {
        return array(
            "state" => $this->stateInfo,
            "url" => $this->fullName,
            "title" => $this->fileName,
            "original" => $this->oriName,
            "type" => $this->fileType,
            "size" => $this->fileSize
        );
    }

}
